package com.test.current;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

public class ProducerAndConsumerDesign {
	public static void main(String[] args) {
		BlockingQueue<String> queue = new LinkedBlockingDeque<String>(10);
		Runnable producer1 = new Producer(queue);
		Runnable producer2 = new Producer(queue);
		Runnable producer3 = new Producer(queue);
		
		Runnable consumer1 = new Consumer(queue);
		Runnable consumer2 = new Consumer(queue);
		Runnable consumer3 = new Consumer(queue);
		Runnable consumer4 = new Consumer(queue);
		ExecutorService service = Executors.newCachedThreadPool();
		service.execute(producer1);
		service.execute(producer2);
		service.execute(producer3);
		service.execute(consumer1);
		service.execute(consumer2);
		service.execute(consumer3);
		service.execute(consumer4);
		service.shutdown();
	
	}
}

class Producer implements Runnable {
	private BlockingQueue<String> queue;

	public Producer(BlockingQueue<String> queue) {
		this.queue = queue;
	}

	@Override
	public void run() {
		Random rom = new Random();
		try {
			Thread.sleep(rom.nextInt(1000));
			queue.put(Thread.currentThread().getId() + " date:" + new Date().getTime());
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

class Consumer implements Runnable {

	private BlockingQueue<String> queue;

	Consumer(BlockingQueue<String> queue) {
		this.queue = queue;
	}

	@Override
	public void run() {
		try {
			Random random = new Random();
			Thread.sleep(random.nextInt(1000));
			String data = queue.take();
			if (data != null) {
				System.out.println("我是消费者:" + Thread.currentThread().getId() + " data:" + data);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

}